﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Tasker.Common
{
    public static class UrlHelper
    {
        public static bool IsAbsoluteUrl(string url)
        {
            Uri result;
            return Uri.TryCreate(url, UriKind.Absolute, out result);
        }

        /// <summary>
        /// Absolutizes given URL with root as specified in <paramref name="domainName"/>
        /// </summary>
        /// <param name="url"></param>
        /// <param name="domainName"></param>
        /// <returns></returns>
        public static string AbsolutizeUrl(string url, string domainName)
        {
            if (url == string.Empty || IsAbsoluteUrl(url))
                return url;

            return domainName
                + (domainName.EndsWith("/") ? "" : "/")	// check for backslash in the end.
                + url;
        }

        public static string ExtractSchemeAndDomain(string url)
        {
            Uri u = new Uri(url);
            return u.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
        }

        public static string ExtractDomain(string url)
        {
            url = NormalizeUrl(url);

            Uri u;
            if (!Uri.TryCreate(url, UriKind.Absolute, out u))
                return url;

            return u.GetComponents(UriComponents.Host, UriFormat.Unescaped);
        }

        public static string NormalizeUrl(string url)
        {
            url = url.Trim().TrimEnd('/');
            if (!url.Contains(@"://"))
                url = "http://" + url;

            return url;
        }

        /// <summary>
        /// Checks if href of an anchor is an URL or not (javascript or link to paragraph).
        /// 
        /// </summary>
        /// <param name="href"></param>
        /// <returns></returns>
        public static bool IsNonUrlHref(string href)
        {
            return (
                href.StartsWith("#")								// anchor.
                 || href.ToLower().StartsWith("javascript:"))	// it could be a javascript function.
                ;
        }


        public static string GetUserPicturePath(string fileName, string fileType = null)
        {
            if (fileName != null /*&& fileType != null*/)
                return Path.Combine(Paths.UserPhotosDir, fileName);
            return Paths.DefaultUserPhoto;
        }

        public static string GetUserPictureThumbPath(string fileName, string fileType = null)
        {
            if (fileName != null /*&& fileType != null*/)
                return Path.Combine(Paths.UserPhotosThumbDir, fileName);
            return Paths.DefaultUserPhoto;
        }
    }
}
